package com.nowcoder.community.service;

import ch.qos.logback.core.util.StringUtil;
import com.nowcoder.community.dao.LoginTicketMapper;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.CommunityContance;
import com.nowcoder.community.util.CommunityUtils;
import com.nowcoder.community.util.MailClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;

@Service
public class UserService implements CommunityContance {

    @Autowired
    private UserMapper userMapper ;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;
    public User findUserById(int id) {
        return userMapper.selectById(id);
    }

    public Map<String, String> register(User user) {
        Map<String, String> map =new HashMap<>();
        if (user ==null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        if(StringUtil.isNullOrEmpty(user.getUsername())) {
            map.put("usernameMsg", "用户名不能为空！");
            return map;
        }

        if(StringUtil.isNullOrEmpty(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }

        if(StringUtil.isNullOrEmpty(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }

        User u = userMapper.selectByName(user.getUsername());
        if (u !=null) {
            map.put("usernameMsg", "用户名已存在！");
            return map;
        }
        u =userMapper.selectByEmail(user.getEmail());
        if (u !=null) {
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }

        user.setSalt(CommunityUtils.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtils.md5(user.getPassword()+user.getSalt()));
        user.setStatus(0);
        user.setType(0);
        user.setActivationCode(CommunityUtils.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        Context context =new Context();
        context.setVariable("email",user.getEmail());
        String url =domain+contextPath+"/activation"+"/"+user.getId()+"/" +user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation",context);
        mailClient.sendMail(user.getEmail(),"激活账号",content);

        return map;
    }

    public int activate(int userId,String activationCode) {
        User user =userMapper.selectById(userId);
        if (user.getStatus()==1) {
            return ACTIVATION_REPEATED;
        }else if (user.getActivationCode().equals(activationCode)) {
            userMapper.updateStatus(userId,1);
            return ACTIVATION_SUCCESS;
        }else{
            return ACTIVATION_FAILURE;
        }
    }

    public Map<String, String> login(String username, String password, int expiredSeconds) {
        Map<String, String> map =new HashMap<>();

        if (StringUtil.isNullOrEmpty(username)) {
            map.put("usernameMsg","账号不能为空");
            return map;
        }

        if (StringUtil.isNullOrEmpty(password)) {
            map.put("passwordMsg","密码不能为空");
            return map;
        }



        User u = userMapper.selectByName(username);
        if (u==null) {
            map.put("usernameMsg","账号不存在");
            return map;
        }

        if (!u.getPassword().equals(CommunityUtils.md5(password+u.getSalt()))) {
            map.put("passwordMsg","密码错误");
            return map;
        }

        if (u.getStatus()==0) {
            map.put("usernameMsg","账号未激活");
            return map;
        }

        LoginTicket loginTicket =new LoginTicket();
        loginTicket.setUserId(u.getId());
        loginTicket.setTicket(CommunityUtils.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis()+expiredSeconds * 1000));

        loginTicketMapper.insertTicket(loginTicket);
        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    public void logout(String ticket) {
        loginTicketMapper.updateStatus(ticket,1);
    }

    public LoginTicket findIdByTicket(String ticket) {
        return loginTicketMapper.selectTicket(ticket);
    }

    public int updateHeader(int userId, String headerUrl) {
        return userMapper.updateHeader(userId,headerUrl);
    }

    public int updatePassword(int userId, String password) {
        return userMapper.updatePassword(userId,CommunityUtils.md5(password+userMapper.selectById(userId).getSalt()));
    }


}
